<?php

namespace Admin\Controller;
use Think\Controller;

// 权限控制器
class AuthorityController extends \Components\AdminController{
	
	// 授权列表
	public function showlist(){
		$list = M('auth')->select();
		$this->assign('list', $list);
		$this->display();
	}

	// 修改权限
	public function update($auth_id){
		$model = M('auth');
		if(IS_POST){
			// 修改操作
			$data = $model->create();
			// 拼接路径
			if ($data['auth_pid'] == 0) {
				$data['auth_c'] = '';
				$data['auth_a'] = '';
				$data['auth_level'] = 0;
				$data['auth_path'] = $auth_id;
			} else {
				$data['auth_level'] = 1;
				$data['auth_path'] = $data['auth_pid'] . '-' . $auth_id;
			}
			if ($model->save($data)) {
				$this->success('修改成功', U('showlist'), 3);
			} else {
				$this->error('修改失败');
			}
			exit();
		}

		// 获取所有父级权限
		$parent_auth = $model->where('auth_level = 0')->select();
		$this->assign('parent_auth', $parent_auth);
		
		// 获取对应的权限实体
		$current_auth = $model->find($auth_id);
		$this->assign('current_auth', $current_auth);

		$this->display();
	}

	// 添加权限
	public function add(){
		$model = M('auth');

		if (IS_POST) {
			// 执行添加操作（auth_path为插入后的id，因此要先add，后update）
			$data = $model->create();
			$data['auth_path'] = '';
			$data['auth_level'] = 0;
			if ($auth_id = $model->add($data)) {// 先执行插入操作
				$info = array();
				if ($data['auth_pid'] == 0) {
					$info['auth_c'] = '';
					$info['auth_a'] = '';
					$info['auth_level'] = 0;
					$info['auth_path'] = $auth_id;
				} else {
					$info['auth_level'] = 1;
					$info['auth_path'] =  $data['auth_pid'] . '-' . $auth_id;
				}
				$info['auth_id'] = $auth_id;
				if ($model->save($info)) {// 修改操作
					$this->success('添加成功', U('showlist'), 3);
				} else {
					$this->error('添加失败');
				}
			} 
			exit();
		}

		// 获取所有父级权限
		$parent_auth = $model->where('auth_level = 0')->select();
		$this->assign('parent_auth', $parent_auth);

		$this->display();
	}
}